﻿#include "BaseGraphicsScene.h"
#include "BaseItemManager.h"
#include <QGraphicsSceneMouseEvent>
#include <QFocusEvent>

namespace OfUI {

	BaseGraphicsScene::BaseGraphicsScene(QObject *parent)
		: QGraphicsScene(parent)
	{
		// 绑定事件过滤器
		installEventFilter(this);
		// 规避QGraphicsScene removeItem 时出现的异常崩溃问题
		setItemIndexMethod(QGraphicsScene::NoIndex);
		// 开启节流计时
		m_moveTime.start();
	}

	BaseGraphicsScene::~BaseGraphicsScene()
	{
	}

	void BaseGraphicsScene::installManager(BaseItemManager* pManager)
	{
		if (pManager)
		{
			m_managerList << pManager;
		}
	}

	void BaseGraphicsScene::removeManager(BaseItemManager * pManager)
	{
		m_managerList.removeOne(pManager);
	}

	bool BaseGraphicsScene::eventFilter(QObject *watched, QEvent *event)
	{
		if (watched == this)
		{
			if (QEvent::GraphicsSceneMousePress == event->type())
			{
				QGraphicsSceneMouseEvent* pMouseEvent = dynamic_cast<QGraphicsSceneMouseEvent*>(event);
				for (auto pManager : m_managerList)
				{
					pManager->mousePressEvent(pMouseEvent);
				}
				return true;
			}
			else if (QEvent::GraphicsSceneMouseRelease == event->type())
			{
				QGraphicsSceneMouseEvent* pMouseEvent = dynamic_cast<QGraphicsSceneMouseEvent*>(event);
				for (auto pManager : m_managerList)
				{
					pManager->mouseReleaseEvent(pMouseEvent);
				}
				return true;
			}
			else if (QEvent::GraphicsSceneMouseMove == event->type())
			{
				if (m_moveTime.elapsed() >= 20)
				{
					m_moveTime.restart();
					QGraphicsSceneMouseEvent* pMouseEvent = dynamic_cast<QGraphicsSceneMouseEvent*>(event);
					for (auto pManager : m_managerList)
					{
						pManager->mouseMoveEvent(pMouseEvent);
					}
				}
				return true;
			}
			else if (QEvent::GraphicsSceneMouseDoubleClick == event->type())
			{
				QGraphicsSceneMouseEvent* pMouseEvent = dynamic_cast<QGraphicsSceneMouseEvent*>(event);
				for (auto pManager : m_managerList)
				{
					pManager->mouseDoubleClickEvent(pMouseEvent);
				}
				return true;
			}
			else if (QEvent::FocusOut == event->type())
			{
				QFocusEvent* pFocusEvet = dynamic_cast<QFocusEvent*>(event);
				for (auto pManager : m_managerList)
				{
					pManager->focusOutEvent(pFocusEvet);
				}
				return true;
			}
			else if (QEvent::WindowDeactivate == event->type())
			{
				QFocusEvent foucsEvent(QEvent::FocusOut, Qt::OtherFocusReason);
				for (auto pManager : m_managerList)
				{
					pManager->focusOutEvent(&foucsEvent);
				}
			}
		}
		return QGraphicsScene::eventFilter(watched, event);
	}

}
